var logger = require('../../common').logger;
var query = require('../../common').Query;
var map = require('../../common').Mapping;
var multiparty = require('multiparty');
var xlsx = require('node-xlsx');
var fs = require("fs");

exports.findProjectPage = function (req, res) {
    var nav = map.navigation[map.userRole[req.session.uid]];
    var user = {
        name: map.userName[req.session.uid],
        role: map.userRole[req.session.uid]
    };
    res.render("findProjectTpl", {nav: nav, user: user});
};

exports.findProjects = function (req, res) {
    query(map.sql.findProjectList, res, req.body, function (rows) {
        if (rows.data) {
            rows.data.forEach(function (e) {
                e.start_date = new Date(e.start_date).Format('yyyy-MM-dd');
                e.end_date = new Date(e.end_date).Format('yyyy-MM-dd');
                e.project_pm = map.userName[e.project_pm];
                e.project_leader = map.userName[e.project_leader];
            });
        } else {
            rows.forEach(function (e) {
                e.start_date = new Date(e.start_date).Format('yyyy-MM-dd');
                e.end_date = new Date(e.end_date).Format('yyyy-MM-dd');
                e.project_pm = map.userName[e.project_pm];
                e.project_leader = map.userName[e.project_leader];
            });
        }
        res.send(rows);
    });
};

exports.findAllProjects = function (req, res) {
    if (!!req.body.all) {
        query("SELECT p_id,p_name FROM project", res, function (rows) {
            res.send(rows);
        });
    } else {
        var statusFilter = [];
        for (var i in map.projectStatus) {
            if (i !== 'cancel' && i !== 'finish') {
                statusFilter.push(i);
            }
        }
        query(map.sql.findProjectList, res, {status: statusFilter}, function (rows) {
            res.send(rows);
        });
    }
};

exports.deleteProjects = function (req, res) {
    query(map.sql.prjBatchDelete, res, req.body, function (rows) {
        if (rows.affectedRows != 0) {
            res.send("success");
        } else {
            res.send({error: 503, description: map.error[503]});
        }
    });
};

exports.addProjectPage = function (req, res) {
    var nav = map.navigation[map.userRole[req.session.uid]];
    var user = {
        name: map.userName[req.session.uid],
        role: map.userRole[req.session.uid]
    };
    res.render("editProjectTpl", {
        nav: nav, user: user, project: {
            p_id: '',
            p_name: '新项目1',
            status: "established",
            start_date: new Date(),
            end_date: new Date(),
            project_pm: '',
            project_leader: ''
        }, list: {}
    });
};

exports.singleAddProjectPage = function (req, res) {
    var nav = map.navigation[map.userRole[req.session.uid]];
    var user = {
        name: map.userName[req.session.uid],
        role: map.userRole[req.session.uid]
    };
    res.render("editProjectTpl", {
        nav: nav, user: user, project: {
            p_id: '',
            p_name: '新项目1',
            status: "established",
            start_date: new Date(),
            end_date: new Date(),
            project_pm: '',
            project_leader: ''
        }
    });
};

exports.addProject = function (req, res) {
    if (req.body instanceof Array) {
        var i = 0;
        (function queryR() {
            if (i < req.body.length) {
                query(map.sql.insertProject, res, req.body[i++], function () {
                });
                queryR();
            } else {
                res.send('success');
            }
        })();
    } else {
        query(map.sql.insertProject, res, req.body, function (rows) {
            res.send('success');
        });
    }
};

exports.editProjectPage = function (req, res) {
    query(map.sql.findProjectList, res, {id: req.params.id}, function (rows) {
        if (rows.length == 1) {
            var nav = map.navigation[map.userRole[req.session.uid]];
            var user = {
                name: map.userName[req.session.uid],
                role: map.userRole[req.session.uid]
            };
            rows[0].project_pm = map.userName[rows[0].project_pm];
            rows[0].project_leader = map.userName[rows[0].project_leader];
            res.render("editProjectTpl", {nav: nav, user: user, project: rows[0]});
        } else {
            res.render('errorTpl', {code: 503, description: map.error[503]})
        }
    });
};

exports.pmEditProjectPage = function (req, res) {
    query(map.sql.findProjectList, res, {project_pm: parseInt(req.session.uid)}, function (rows) {
        if (rows.length >= 1) {
            var nav = map.navigation[map.userRole[req.session.uid]];
            var user = {
                name: map.userName[req.session.uid],
                role: map.userRole[req.session.uid]
            };
            rows[0].project_pm = map.userName[rows[0].project_pm];
            rows[0].project_leader = map.userName[rows[0].project_leader];
            res.render("batchEditProjectTpl", {nav: nav, user: user, project: rows[0], list: rows});
        } else {
            res.send('<span style="color: red;position: relative;left:40px;">暂没有担任任何项目的项目经理</span>');
        }
    })
};

exports.saveProjects = function (req, res) {
    query(map.sql.updateProject, res, req.body, function (rows) {
        if (rows.affectedRows != 0) {
            res.send("success");
        } else {
            res.send({error: 503, description: map.error[503]});
        }
    });
};

exports.uploadForm = function (req, res) {
    function dataComplete(object) {
        var valid = true;
        if(object.length < 6) {
            return false;
        }
        for(var i = 0;i<6;i++) {
            if(!object[i] || (object[i].trim && object[i].trim().length == 0)) {
                valid = false;
            }
        }
        return valid;
    }

    var form = new multiparty.Form({uploadDir: './app/temp/'});
    form.parse(req, function (err, fields, files) {
        if (err) {
            console.log('parse error: ' + err);
            res.send(map.error[503]);
        } else {
            var tempFile = files['file'][0];
            logger.info("Upload File : " + tempFile.originalFilename);

            var obj = xlsx.parse(tempFile.path);
            fs.unlink(tempFile.path);

            var insertArray = [], project = null;
            var userR = {},statusR = {},projectMap = {};
            for(var i in map.userName){
                userR[map.userName[i]] = parseInt(i);
            }
            for(var i in map.projectStatus) {
                statusR[map.projectStatus[i]] = i;
            }
            query("SELECT p_name FROM project",res,{},function(data){
                data.forEach(function(ele){
                    projectMap[ele.p_name] = true;
                });

                if (obj[0] && obj[0].data && obj[0].data.length > 0) {
                    //step1 : validate all data and push to array.
                    for (var i = 2; i < obj[0].data.length; i++) {
                        project = obj[0].data[i];
                        if (!!project[0]) {
                            if(!dataComplete(project)) {
                                res.send(map.error[506]);
                                return;
                            }
                            //user map reverse, p_status reverse, date. insert. query all project->map, unique check
                            if(!(project[0] in projectMap)) {
                                project[1] = userR[project[1]];
                                project[2] = userR[project[2]];
                                project[3] = statusR[project[3]];
                                if(!!project[1] && !!project[2] && !!project[3]) {
                                    insertArray.push({
                                        p_name : project[0],
                                        status : project[3],
                                        project_pm : project[1],
                                        project_leader : project[2],
                                        start_date : project[4],
                                        end_date : project[5]
                                    })
                                } else {
                                    res.send(map.error[506]);
                                    return;
                                }
                            } else {
                                res.send(map.error[507]);
                                return;
                            }
                        } else {
                            if (i == 2) {
                                res.send(map.error[505]);
                            } else {
                                break;
                            }
                        }
                    }

                    //step2 : insert all projects in excel
                    var cursor = 0;
                    (function queryR() {
                        if (cursor < insertArray.length) {
                            query(map.sql.insertProject, res, insertArray[cursor++], function () {
                            });
                            queryR();
                        } else {
                            res.send('success');
                        }
                    })();
                }
            });
        }
    });
};